package com.suyang.syt.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class OracleUtil {
	private OracleUtil() {
	}

	/**
	 * 数据库驱动字符串
	 */
	private static String driver = "oracle.jdbc.driver.OracleDriver";
	/**
	 * 连接URL字符串
	 */ 
	private static String url = "jdbc:oracle:thin:@192.168.1.140:1521:ORCL";
	/**
	 * 数据库用户名
	 */ 
	private static String user = "csyj";
	/**
	 * 用户密码
	 */ 
	private static String password = "csyj";

	/**
	 * 获取数据库连接对象
	 * @return 数据库连接对象
	 */
	public static Connection getConnection() {
		Connection connection = null;
		try {
			Class.forName(driver); // 加载驱动
			connection = DriverManager.getConnection(url, user, password); // 获得数据库链接
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}

	/**
	 * 关闭数据库连接
	 * @param connection 数据库链接
	 * @param statement statement对象
	 * @param resultSet 结果集
	 */
	public static void closeAll(Connection connection, Statement statement,	ResultSet resultSet) {
		// 若结果集不为空，则关闭
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// 若Statement对象不为空，则关闭
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// 若数据库连接对象不为空，则关闭
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 关闭数据库连接
	 * @param connection 数据库链接
	 * @param preparedStatement	preparedStatement对象
	 * @param resultSet 结果集
	 */
	public static void closeAll(Connection connection,PreparedStatement preparedStatement, ResultSet resultSet) {
		// 若结果集不为空，则关闭
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// 若preparedStatement对象不为空，则关闭
		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// 若数据库连接对象不为空，则关闭
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}	
}
